import numpy as np
import os
import mcubes

from PyCmpltrtok.common import sep, get_dir_name_ext, rand_name_on_now
from PyCmpltrtok.common_3d import add_sphere, render_base_planes, render_landmark_for_xyz, take_trunk_by_scale

scale = 0.09837138047213126
N = 256

# x1 = 0.
# x2 = 1.
# y1 = 0.
# y2 = 1.
# z1 = 0.
# z2 = 1.
x1 = 0.4
x2 = 0.67
y1 = 0.2
y2 = 0.6
z1 = 0.6
z2 = 0.9

tx1, tx2, ty1, ty2, tz1, tz2 = take_trunk_by_scale((x1, x2, y1, y2, z1, z2), -scale, scale)

tx = np.linspace(tx1, tx2, N)
ty = np.linspace(ty1, ty2, N)
tz = np.linspace(tz1, tz2, N)

sep('volume rendering')
X, Y, Z = np.meshgrid(tx, ty, tz, indexing='ij', sparse=True)  # Test: sparse = True/False
sigma = np.zeros([N, N, N], dtype=np.float32)

sep('Render sphere')
cx, cy, cz, r = 0.5, 0.25, 0.9, 0.6
add_sphere(sigma, X, Y, Z, cx, cy, cz, r)

sep('Render base planes')
render_base_planes(sigma)
render_landmark_for_xyz(sigma, X, Y, Z)

sep('marching cubes')
vertices, triangles = mcubes.marching_cubes(sigma, 0)
xdir, xname, xext = get_dir_name_ext(os.path.abspath(__file__))
xdir4save = os.path.join(xdir, '_save', xname)
os.makedirs(xdir4save, exist_ok=True)
path = os.path.join(xdir4save, f'N{N}_scale{scale}_{xname}.dt{rand_name_on_now()}.dae')
print(f'Saving to {path}')
mcubes.export_mesh(vertices, triangles, path, xname)
print('Saved')

sep('All over')
